# -*- coding: utf-8 -*-
import json,os,logging,traceback, time, threading
from jinja2 import Markup
from flask import flash, url_for, redirect, request, current_app
from flask_admin.base import expose
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction
from flask_wtf import FlaskForm
from sqlalchemy import func
from wtforms import SelectMultipleField, ValidationError
from wtforms.validators import DataRequired
from flask_admin.actions import action
from flask_admin.helpers import (get_form_data, validate_form_on_submit,get_redirect_target, flash_errors)
from flask_admin.contrib.sqla import form, filters as sqla_filters, tools
from . import MyModelView
from . import AjaxQueryIndexLike
from adminApp.extensions import db, redis_store
from wtforms import PasswordField, TextField, ValidationError,StringField
from adminApp.models import Machine,Idc


logger = logging.getLogger(__name__)

class TimedTasksView(MyModelView):
    column_filters = ('id', 'name', 'task_type', 'status')

    column_list = ('id', 'name', 'task_type', 'status', 'exec_time','remark','last_run', 'created', 'updated')
    # column_sortable_list = (
    #     'id', 'name', 'category.name', 'author.name', 'serial_state', 'words', 'last_updated', 'created')

    # task_type = Column(String(512), default="shell")
    #     name = Column(String(512))
    #     status = Column(String(512))
    #     command_txt = Column(Text)
    #     target_machine_ids = Column(Text)
    #     remark = Column(Text)
    #     exec_time = Column(String(64))  # 每天的执行时间 小时分钟  18:00

    column_labels = {
        'name': '任务名称',
        'task_type': '任务类型',
        'status': '任务状态',
        'exec_time': '执行时间',
        'remark': '备注',
        'created': '创建日期',
        'updated': '最后更新',
        'target_machine_ids':'任务设备ID'
    }

    column_formatters = dict(
        last_run=lambda v, c, m, p: m.last_run.strftime("%Y-%m-%d %H:%M") if m.last_run else '',
        created=lambda v, c, m, p: m.created.strftime("%Y-%m-%d %H:%M:%S"),
        updated=lambda v, c, m, p: m.updated.strftime("%Y-%m-%d %H:%M:%S") if m.updated else ''
    )
    column_editable_list = ('name','status','command_txt','exec_time','remark')
    # form_columns = ('name','status','command_txt','exec_time','remark')
    edit_template = 'timed_tasks/edit.html'
    create_template = 'timed_tasks/create.html'
    form_args = dict(
        name=dict(validators=[DataRequired()]),
        command_txt=dict(validators=[DataRequired()]),
        exec_time=dict(validators=[DataRequired()]),
    )

    form_extra_fields = {
        'idc': StringField('机房名称'),
        'idc_son': StringField('机房分段'),
        'hostname': StringField('主机名称'),
        'mark': StringField('设备标识'),
        'machine_ID': StringField('设备记录ID'),
    }
    form_widget_args = dict(
        name=dict(
            placeholder='任务名称',
        ),
        exec_time=dict(
            placeholder='时间格式：01:05 (代表1点5分钟的时候执行，使用24小时制，暂时只支持每天定时执行)',
        ),
        machine_ID=dict(
            placeholder='要执行计划任务的设备记录ID，多个ID请使用","分割',
        ),
        idc=dict(
            placeholder='用于查询设备的参数',
        ),
        idc_son=dict(
            placeholder='用于查询设备的参数',
        ),
        mark=dict(
            placeholder='用于查询设备的参数',
        ),
        hostname=dict(
            placeholder='用于查询设备的参数',
        ),
        command_txt=dict(
            placeholder='要执行的脚本，请填写shell脚本',
        ),
    )

    form_create_rules = _rules = ['name', 'status', 'command_txt', 'idc', 'idc_son', 'hostname', 'mark', 'machine_ID', 'target_machine_ids','exec_time', 'remark']
    form_edit_rules = ['name', 'status', 'command_txt', 'idc', 'idc_son', 'hostname', 'mark', 'machine_ID', 'target_machine_ids','exec_time', 'remark']

    @expose('/get_target_ids', methods=('POST',))
    def get_target_ids(self):
        result = dict()
        idc = request.form.get('idc')
        idc_son = request.form.get('idc_son')
        hostname = request.form.get('hostname')
        mark = request.form.get('mark')
        machine_ID = request.form.get('machine_ID')
        if idc or idc_son or hostname or mark or machine_ID:
            q=db.session.query(Machine.id,Machine.system_uuid).join(Idc,isouter=True)
            if idc:
                q = q.filter(Idc.name.like('%{}%'.format(idc)))
            if idc_son:
                q = q.filter(Idc.mark.like('%{}%'.format(idc_son)))
            if hostname:
                q = q.filter(Machine.hostname.like('%{}%'.format(hostname)))
            if mark:
                q = q.filter(Machine.man_mark.like('%{}%'.format(mark)))
            if machine_ID:
                aids = machine_ID.split(',')
                faids =[]
                for ad in aids:
                    try:
                        faids.append(int(ad))
                    except:
                        pass
                if faids:
                    q = q.filter(Machine.id.in_(faids))
            result = {r[0]:r[1] for r in q.all()}
        return json.dumps(result)